<template>
  <div class="issue-list">
    <div class="page-header">
      <div class="header-left">
        <h1>问题管理</h1>
        <p>跟踪和解决项目中的问题</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="createIssue">
          <el-icon><Plus /></el-icon>
          报告问题
        </el-button>
      </div>
    </div>
    
    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索问题标题或描述"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="filter-right">
        <el-select
          v-model="statusFilter"
          placeholder="问题状态"
          style="width: 120px"
          clearable
          @change="handleFilter"
        >
          <el-option label="待处理" value="待处理" />
          <el-option label="处理中" value="处理中" />
          <el-option label="已解决" value="已解决" />
          <el-option label="已关闭" value="已关闭" />
          <el-option label="重新打开" value="重新打开" />
        </el-select>
        
        <el-select
          v-model="priorityFilter"
          placeholder="优先级"
          style="width: 100px"
          clearable
          @change="handleFilter"
        >
          <el-option label="紧急" value="urgent" />
          <el-option label="高" value="high" />
          <el-option label="中" value="medium" />
          <el-option label="低" value="low" />
        </el-select>
        
        <el-select
          v-model="typeFilter"
          placeholder="问题类型"
          style="width: 120px"
          clearable
          @change="handleFilter"
        >
          <el-option label="Bug" value="bug" />
          <el-option label="功能请求" value="feature" />
          <el-option label="改进" value="improvement" />
          <el-option label="任务" value="task" />
        </el-select>
        
        <el-select
          v-model="projectFilter"
          placeholder="所属项目"
          style="width: 150px"
          clearable
          @change="handleFilter"
        >
          <el-option
            v-for="project in projects"
            :key="project.id"
            :label="project.name"
            :value="project.id"
          />
        </el-select>
        
        <el-button @click="resetFilters">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </div>
    </div>
    
    <!-- 统计信息 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-number">{{ totalIssues }}</div>
        <div class="stat-label">总问题数</div>
      </div>
      <div class="stat-card">
        <div class="stat-number">{{ openIssues }}</div>
        <div class="stat-label">待处理</div>
      </div>
      <div class="stat-card">
        <div class="stat-number">{{ inProgressIssues }}</div>
        <div class="stat-label">处理中</div>
      </div>
      <div class="stat-card">
        <div class="stat-number">{{ resolvedIssues }}</div>
        <div class="stat-label">已解决</div>
      </div>
      <div class="stat-card">
        <div class="stat-number">{{ closedIssues }}</div>
        <div class="stat-label">已关闭</div>
      </div>
    </div>
    
    <!-- 问题列表 -->
    <div class="issues-table" v-loading="loading">
      <el-table
        :data="filteredIssues"
        style="width: 100%"
        @row-click="viewIssue"
        row-class-name="issue-row"
      >
        <el-table-column prop="id" label="ID" width="80">
          <template #default="{ row }">
            <span class="issue-id">#{{ row.id }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="title" label="问题标题" min-width="250">
          <template #default="{ row }">
            <div class="issue-title">
              <div class="priority-indicator" :class="row.priority"></div>
              <div class="title-content">
                <span class="title-text">{{ row.title }}</span>
                <div class="issue-labels">
                  <el-tag
                    :type="getTypeColor(row.type)"
                    size="small"
                    effect="plain"
                  >
                    {{ getTypeText(row.type) }}
                  </el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="project" label="所属项目" width="150">
          <template #default="{ row }">
            <el-tag size="small" effect="plain">
              {{ row.project?.name || '未分配' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="reporter" label="报告人" width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="24">
                {{ row.reporter.username.charAt(0).toUpperCase() }}
              </el-avatar>
              <span>{{ row.reporter.username }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="assignee" label="负责人" width="120">
          <template #default="{ row }">
            <div class="user-info" v-if="row.assignee">
              <el-avatar :size="24">
                {{ row.assignee.username.charAt(0).toUpperCase() }}
              </el-avatar>
              <span>{{ row.assignee.username }}</span>
            </div>
            <span v-else class="unassigned">未分配</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="{ row }">
            <el-tag
              :type="getPriorityType(row.priority)"
              size="small"
              effect="plain"
            >
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="updatedAt" label="更新时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.updatedAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-dropdown @command="handleCommand">
              <el-button text>
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'view', id: row.id }">
                    <el-icon><View /></el-icon>
                    查看详情
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'edit', id: row.id }">
                    <el-icon><Edit /></el-icon>
                    编辑问题
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'assign', id: row.id }">
                    <el-icon><User /></el-icon>
                    分配问题
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'resolve', id: row.id }"
                    v-if="row.status !== '已解决' && row.status !== '已关闭'"
                  >
                    <el-icon><Check /></el-icon>
                    标记解决
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'close', id: row.id }"
                    v-if="row.status !== '已关闭'"
                  >
                    <el-icon><Lock /></el-icon>
                    关闭问题
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'reopen', id: row.id }"
                    v-if="row.status === '已关闭'"
                  >
                    <el-icon><Unlock /></el-icon>
                    重新打开
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'delete', id: row.id }"
                    divided
                  >
                    <el-icon><Delete /></el-icon>
                    删除问题
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 空状态 -->
    <div class="empty-state" v-if="!loading && filteredIssues.length === 0">
      <el-empty description="暂无问题数据">
        <el-button type="primary" @click="createIssue">
          报告第一个问题
        </el-button>
      </el-empty>
    </div>
    
    <!-- 分页 -->
    <div class="pagination" v-if="filteredIssues.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import {
  Plus,
  Search,
  Refresh,
  MoreFilled,
  View,
  Edit,
  Delete,
  User,
  Check,
  Lock,
  Unlock
} from '@element-plus/icons-vue'

const router = useRouter()


const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const priorityFilter = ref('')
const typeFilter = ref('')
const projectFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 项目列表
const projects = ref([
  { id: 1, name: '项目管理系统' },
  { id: 2, name: '电商平台' },
  { id: 3, name: '移动应用开发' }
])

// 模拟问题数据
const issues = ref([
  {
    id: 1,
    title: '用户登录页面样式错乱',
    description: '在Chrome浏览器中，登录页面的样式显示不正常，按钮位置偏移',
    type: 'bug',
    status: '待处理',
    priority: 'high',
    project: { id: 1, name: '项目管理系统' },
    reporter: { id: 1, username: '张三' },
    assignee: { id: 2, username: '李四' },
    createdAt: new Date('2024-01-15'),
    updatedAt: new Date('2024-01-15')
  },
  {
    id: 2,
    title: '添加任务导出功能',
    description: '希望能够将任务列表导出为Excel文件，方便离线查看和分析',
    type: 'feature',
    status: '处理中',
    priority: 'medium',
    project: { id: 1, name: '项目管理系统' },
    reporter: { id: 3, username: '王五' },
    assignee: { id: 1, username: '张三' },
    createdAt: new Date('2024-01-14'),
    updatedAt: new Date('2024-01-16')
  },
  {
    id: 3,
    title: '数据库查询性能优化',
    description: '项目列表页面加载速度较慢，需要优化数据库查询性能',
    type: 'improvement',
    status: '已解决',
    priority: 'medium',
    project: { id: 1, name: '项目管理系统' },
    reporter: { id: 2, username: '李四' },
    assignee: { id: 1, username: '张三' },
    createdAt: new Date('2024-01-12'),
    updatedAt: new Date('2024-01-16')
  },
  {
    id: 4,
    title: '系统崩溃问题',
    description: '在大量并发用户访问时，系统出现崩溃现象',
    type: 'bug',
    status: '处理中',
    priority: 'urgent',
    project: { id: 1, name: '项目管理系统' },
    reporter: { id: 4, username: '赵六' },
    assignee: { id: 1, username: '张三' },
    createdAt: new Date('2024-01-16'),
    updatedAt: new Date('2024-01-17')
  },
  {
    id: 5,
    title: '移动端适配问题',
    description: '在移动设备上访问时，页面布局显示不正常',
    type: 'bug',
    status: '已关闭',
    priority: 'low',
    project: { id: 1, name: '项目管理系统' },
    reporter: { id: 3, username: '王五' },
    assignee: null,
    createdAt: new Date('2024-01-10'),
    updatedAt: new Date('2024-01-15')
  },
  {
    id: 6,
    title: '增加暗色主题支持',
    description: '希望系统能够支持暗色主题，提升夜间使用体验',
    type: 'feature',
    status: '待处理',
    priority: 'low',
    project: { id: 1, name: '项目管理系统' },
    reporter: { id: 5, username: '钱七' },
    assignee: null,
    createdAt: new Date('2024-01-17'),
    updatedAt: new Date('2024-01-17')
  }
])

// 过滤后的问题列表
const filteredIssues = computed(() => {
  let result = issues.value
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(issue => 
      issue.title.toLowerCase().includes(query) ||
      (issue.description && issue.description.toLowerCase().includes(query))
    )
  }
  
  // 状态过滤
  if (statusFilter.value) {
    result = result.filter(issue => issue.status === statusFilter.value)
  }
  
  // 优先级过滤
  if (priorityFilter.value) {
    result = result.filter(issue => issue.priority === priorityFilter.value)
  }
  
  // 类型过滤
  if (typeFilter.value) {
    result = result.filter(issue => issue.type === typeFilter.value)
  }
  
  // 项目过滤
  if (projectFilter.value) {
    result = result.filter(issue => issue.project?.id === Number(projectFilter.value))
  }
  
  total.value = result.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 统计数据
const totalIssues = computed(() => issues.value.length)
const openIssues = computed(() => issues.value.filter(issue => issue.status === '待处理').length)
const inProgressIssues = computed(() => issues.value.filter(issue => issue.status === '处理中').length)
const resolvedIssues = computed(() => issues.value.filter(issue => issue.status === '已解决').length)
const closedIssues = computed(() => issues.value.filter(issue => issue.status === '已关闭').length)

// 获取状态类型
const getStatusType = (status: string): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
  const types: Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'> = {
    '待处理': 'info',
    '处理中': 'warning',
    '已解决': 'success',
    '已关闭': 'info',
    '重新打开': 'danger'
  }
  return types[status] || 'info'
}

// 获取优先级类型
const getPriorityType = (priority: string): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
  const types: Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'> = {
    'urgent': 'danger',
    'high': 'danger',
    'medium': 'warning',
    'low': 'success'
  }
  return types[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const texts: Record<string, string> = {
    'urgent': '紧急',
    'high': '高',
    'medium': '中',
    'low': '低'
  }
  return texts[priority] || priority
}

// 获取类型颜色
const getTypeColor = (type: string): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
  const colors: Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'> = {
    'bug': 'danger',
    'feature': 'primary',
    'improvement': 'success',
    'task': 'warning'
  }
  return colors[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const texts: Record<string, string> = {
    'bug': 'Bug',
    'feature': '功能请求',
    'improvement': '改进',
    'task': '任务'
  }
  return texts[type] || type
}

// 格式化日期
const formatDate = (date: Date) => {
  return dayjs(date).format('MM-DD HH:mm')
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
}

// 重置筛选
const resetFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  priorityFilter.value = ''
  typeFilter.value = ''
  projectFilter.value = ''
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 操作处理
const handleCommand = (command: { action: string; id: number }) => {
  const { action, id } = command
  
  switch (action) {
    case 'view':
      viewIssueById(id)
      break
    case 'edit':
      editIssue(id)
      break
    case 'assign':
      assignIssue(id)
      break
    case 'resolve':
      resolveIssue(id)
      break
    case 'close':
      closeIssue(id)
      break
    case 'reopen':
      reopenIssue(id)
      break
    case 'delete':
      deleteIssue(id)
      break
  }
}

// 查看问题
const viewIssue = (issue: any) => {
  router.push(`/issues/${issue.id}`)
}

const viewIssueById = (id: number) => {
  router.push(`/issues/${id}`)
}

// 编辑问题
const editIssue = (id: number) => {
  router.push(`/issues/${id}/edit`)
}

// 分配问题
const assignIssue = (id: number) => {
  router.push(`/issues/${id}/assign`)
}

// 解决问题
const resolveIssue = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要将此问题标记为已解决吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    const issue = issues.value.find(i => i.id === id)
    if (issue) {
      issue.status = '已解决'
      issue.updatedAt = new Date()
    }
    
    ElMessage.success('问题已标记为解决')
  } catch {
    // 用户取消操作
  }
}

// 关闭问题
const closeIssue = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要关闭此问题吗？关闭后问题将不再显示在活跃列表中。',
      '确认关闭',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const issue = issues.value.find(i => i.id === id)
    if (issue) {
      issue.status = '已关闭'
      issue.updatedAt = new Date()
    }
    
    ElMessage.success('问题已关闭')
  } catch {
    // 用户取消操作
  }
}

// 重新打开问题
const reopenIssue = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要重新打开此问题吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    const issue = issues.value.find(i => i.id === id)
    if (issue) {
      issue.status = '重新打开'
      issue.updatedAt = new Date()
    }
    
    ElMessage.success('问题已重新打开')
  } catch {
    // 用户取消操作
  }
}

// 删除问题
const deleteIssue = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个问题吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    issues.value = issues.value.filter(i => i.id !== id)
    ElMessage.success('问题删除成功')
  } catch {
    // 用户取消删除
  }
}

// 创建问题
const createIssue = () => {
  router.push('/issues/create')
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 这里应该调用API加载问题数据
    // await issueStore.fetchIssues()
    await new Promise(resolve => setTimeout(resolve, 500))
  } catch (error) {
    console.error('加载问题数据失败:', error)
    ElMessage.error('加载问题数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.issue-list {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-right {
  display: flex;
  gap: 12px;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.issues-table {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.issue-id {
  font-weight: 600;
  color: #409eff;
}

.issue-title {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.priority-indicator {
  width: 4px;
  height: 16px;
  border-radius: 2px;
  margin-top: 2px;
  flex-shrink: 0;
}

.priority-indicator.urgent {
  background: #ff4757;
}

.priority-indicator.high {
  background: #f56c6c;
}

.priority-indicator.medium {
  background: #e6a23c;
}

.priority-indicator.low {
  background: #67c23a;
}

.title-content {
  flex: 1;
}

.title-text {
  display: block;
  margin-bottom: 4px;
  font-weight: 500;
}

.issue-labels {
  display: flex;
  gap: 4px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.unassigned {
  color: #999;
  font-style: italic;
}

:deep(.issue-row) {
  cursor: pointer;
}

:deep(.issue-row:hover) {
  background-color: #f5f7fa;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-section {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-section {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-right {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .stats-section {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .stats-section {
    grid-template-columns: 1fr;
  }
}
</style>